package lion.framework.core.db.datasource;

import javax.sql.DataSource;

import lion.dev.lang.MapJ;
import lion.framework.core.db.DataSourceManager;
import lion.framework.core.db.anno.DataSourceProvider;

import org.apache.commons.dbcp.BasicDataSource;

/**
 * DBCP连接池获取类<br/>
 * 如果max属性不设置或设置为负数，则不限制最大连接数
 *
 * <pre>
 * time   2013年8月6日
 * mail   hl_0074@sina.com
 * </pre>
 *
 * @author lion
 */
@DataSourceProvider("dbcp")
public class DBCPDataSourceProvider implements IDataSourceProvider {

	private MapJ config;

	public DBCPDataSourceProvider(MapJ config) {

		this.config = config;
	}

	@Override
	public DataSource getDataSource() {

		BasicDataSource ds = new BasicDataSource();
		ds.setUsername(config.getString("user"));
		ds.setPassword(config.getString("password"));
		ds.setUrl(String.format(DataSourceManager.getDriverURLTemplate(config.getString("type", "mysql")), config.getString("server", "localhost"), config.getInt("port", 3306),
				config.getString("db")));

		ds.setDriverClassName(DataSourceManager.getJDBCDriver(config.getString("type")));
		ds.setInitialSize(config.getInt("init", 10));
		ds.setMaxActive(config.getInt("max"));
		ds.setPoolPreparedStatements(true);

		return ds;
	}

}
